package com.shoujifeng.snowmusic.player;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.security.auth.PrivateCredentialPermission;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;

import com.geniuseoe2012.lazyloaderdemo.cache.MusicPlayerImageLoader;
import com.shoujifeng.snowmusic.adapter.MusicPlayMusicAdapter;
import com.shoujifeng.snowmusic.adapter.MyPagerAdapter;
import com.shoujifeng.snowmusic.adapter.OnlineListAdapter;
import com.shoujifeng.snowmusic.db.DatabaseUtil;
import com.shoujifeng.snowmusic.player.http.GlobalValue;
import com.shoujifeng.snowmusic.player.http.ServerAccess;
import com.shoujifeng.snowmusic.player.interfaces.MoreInterface;
import com.shoujifeng.snowmusic.player.interfaces.MusicPlayMoreInterface;
import com.shoujifeng.snowmusic.player.interfaces.PlayerInterface;
import com.shoujifeng.snowmusic.player.utils.LoadMask;
import com.shoujifeng.snowmusic.player.utils.MusicPlayer;

public class MusicPlayerActivity extends Activity implements
		SensorEventListener {
	// 翻页控件
	private ViewPager mViewPager;
	// 3个是底部显示当前状态点imageView
	private ImageView mPage0;
	private ImageView mPage1;
	private ImageView mPage2;
	private MusicPlayer musicPlayer;
	private static MusicPlayerImageLoader mImageLoader;
	
	private Button playBtn;
	private Button moreBtn;
	private Button lastMusicBtn;
	private Button nextBtn;
	private Button shuffleMusicBtn;
	private Button moreShareBtn;
	private Button moreAlbumBtn;
	private Button moreAddBtn;
	private Button moreSingerBtn;
	
	private static ImageView image1;
	private static ImageView image2;
	private static ImageView image3;
	
	public static TextView lay3_musicName;
	public static TextView lay3_playerName;
	private ListView musicListView;
	private MusicPlayMusicAdapter mAdapter;
	public static LrcView lrc_view;
	private SensorManager sensorManager;
	private float lastX, lastY, lastZ;                   // 记录上一次震动位置
	private static final int SPEED_SHRESHOLD = 2000;     // 速度阈值，当摇晃速度达到这值后产生作用
	private static final int UPTATE_INTERVAL_TIME = 70;  // 两次检测的时间间隔
	private long lastUpdateTime;                         // 上次检测时间
	private List<HashMap<String, String>> musiclist;
	private int mPosition;
	private ImageButton downImgBtn;
	private LinearLayout moreLay;
	public static SeekBar progressBar;
	public static TextView whenTxt;
	public static TextView countTimeTxt;
	public static String videoUrl = "";
	public static ArrayList<HashMap<String, Object>> mOlineMusicList = new ArrayList<HashMap<String, Object>>();
	public static int mOnlineMusicNo = 0;
	public static boolean isOnline = false;
	private int videoLength;
	private ServerAccess serverAccess;
	private Thread accThread;
	private String index = "no";
	private String album = "";
	private String singer ="";
	private LoadMask mLoadMask;
	private final int UPDATE_DATA = 0;
	private String netDate = "";
	private String getSingerOrAblum =""; //是查看歌曲还是专辑
	
	public static LoadMask LOADMASK;
	
	private int music_uid = -1;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// 去掉标题栏全屏显示
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.music_play_4);
		
		if(LOADMASK == null)
			LOADMASK = new LoadMask(this);
		
		init();
		mImageLoader = new MusicPlayerImageLoader(MusicPlayerActivity.this);
		
		initGlobalValue();
		
		MusicPlayer.PLAY_ORDER = 0;
		
		if(mAdapter.getCount() > 0)
		{	
			sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
			
			setTextView();
			mLoadMask = new LoadMask(this);
			
			ShareSDK.initSDK(this);
			
			setStartPlayMusic();    //开始播放
		}
		setMusicImg();
		if(MusicPlayer.isPlaying==false){
			playBtn.setBackgroundResource(R.drawable.btn_playing_normal);
		}
	}
	
	@Override
	protected void onDestroy() {
		
		if(mAdapter.getCount() > 0){
			ShareSDK.stopSDK(this);
		}
		
		super.onDestroy();
	}
	
	

	@Override
	protected void onPause() {
		PlayService.mInterface = null;
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		if(mAdapter.getCount() > 0) {
			musicListView.setSelection(MusicPlayer.position);
			
			// 注册传感器监听，监听加速器
			sensorManager.registerListener(this,
					sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
					SensorManager.SENSOR_DELAY_GAME);
			
			PlayService.mInterface = playerInterface;
		}
	}

	public void init() {
		serverAccess = new ServerAccess(MusicPlayerActivity.this);
		
		mViewPager = (ViewPager) findViewById(R.id.whatsnew_viewpager);

		mViewPager.setOnPageChangeListener(new MyOnPageChangeListener());
		mPage0 = (ImageView) findViewById(R.id.page0);
		mPage1 = (ImageView) findViewById(R.id.page1);
		mPage2 = (ImageView) findViewById(R.id.page2);

		/*
		 * 这里是每一页要显示的布局，根据应用需要和特点自由设计显示的内容 以及需要显示多少页等
		 */
		LayoutInflater mLi = LayoutInflater.from(this);
		View view1 = mLi.inflate(R.layout.music_play_3, null);
		View view2 = mLi.inflate(R.layout.music_play_1, null);
		View view3 = mLi.inflate(R.layout.music_play_2, null);

		lay3_musicName = (TextView) view2.findViewById(R.id.music_name);
		lay3_playerName = (TextView) view2.findViewById(R.id.player_name);
		
		image1 = (ImageView) view1.findViewById(R.id.player_head);
		image2 = (ImageView) view2.findViewById(R.id.player_head2);
		image3 = (ImageView) view3.findViewById(R.id.player_head3);
		
		lrc_view = (LrcView) view3.findViewById(R.id.lrcShow);
		
		Button btnCollect = (Button) view2.findViewById(R.id.collect_btn);
		Button btnDownload = (Button) view2.findViewById(R.id.download_btn);
		btnCollect.setOnClickListener(v2OnClickListener);
		btnDownload.setOnClickListener(v2OnClickListener);
		/*
		 * 这里将每一页显示的view存放到ArrayList集合中 可以在ViewPager适配器中顺序调用展示
		 */
		final ArrayList<View> views = new ArrayList<View>();

		views.add(view1);
		views.add(view2);
		views.add(view3);

		/*
		 * 每个页面的Title数据存放到ArrayList集合中 可以在ViewPager适配器中调用展示
		 */
		final ArrayList<String> titles = new ArrayList<String>();
		titles.add("tab1");
		titles.add("tab2");
		titles.add("tab3");

		// 填充ViewPager的数据适配器
		MyPagerAdapter mPagerAdapter = new MyPagerAdapter(views, titles);
		mViewPager.setAdapter(mPagerAdapter);

		progressBar = (SeekBar) findViewById(R.id.progressBar);
		whenTxt = (TextView) findViewById(R.id.whenTxt);
		countTimeTxt = (TextView) findViewById(R.id.countTimeTxt);
		playBtn = (Button) findViewById(R.id.playBtn);
		lastMusicBtn = (Button) findViewById(R.id.last_music);
		nextBtn = (Button) findViewById(R.id.next_music);
		shuffleMusicBtn = (Button) findViewById(R.id.shuffle_music);
		musicListView = (ListView) view1.findViewById(R.id.musicPlayList);
		moreBtn = (Button) findViewById(R.id.smaller_menus);
		moreLay = (LinearLayout) findViewById(R.id.moreLay);
		
//		分享  专辑  添加到 歌手  
		moreShareBtn = (Button) findViewById(R.id.music_play_share_btn);
		moreAlbumBtn = (Button) findViewById(R.id.music_play_album_btn);
		moreAddBtn = (Button) findViewById(R.id.music_play_add_btn);
		moreSingerBtn = (Button) findViewById(R.id.music_play_singer_btn);
		moreShareBtn.setOnClickListener(onClickListener);
		moreAlbumBtn.setOnClickListener(onClickListener);
		moreAddBtn.setOnClickListener(onClickListener);
		moreSingerBtn.setOnClickListener(onClickListener);

		playBtn.setOnClickListener(onClickListener);
		lastMusicBtn.setOnClickListener(onClickListener);
		nextBtn.setOnClickListener(onClickListener);
		shuffleMusicBtn.setOnClickListener(onClickListener);
		moreBtn.setOnClickListener(onClickListener);
		setListView();
		musicListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				ImageView playerHead = (ImageView) view
						.findViewById(R.id.playerHead);
				// 显示和隐藏歌手的头像
				setTextView();
				MusicPlayer.MUSCI_MSG = 1;
				musicPlayer.startPlay();
				mPosition = position;
				MusicPlayer.position = position;
				mAdapter.notifyDataSetChanged();
			}
		});
		downImgBtn = (ImageButton) findViewById(R.id.downImgBtn);
		downImgBtn.setOnClickListener(onClickListener);
		
		progressBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				videoLength = seekBar.getProgress();
				PlayService.mediaPlayer.seekTo(videoLength);
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
			//	PlayService.mediaPlayer.seekTo(seekBar.getProgress()); 
				
			}
		});
		
	}
	
	private void setStartPlayMusic(){
		
		try {
			musicPlayer = new MusicPlayer(MusicPlayerActivity.this);
			if(MusicPlayer.isPlaying&&ServerAccess.activityName.equals("MyTabHost")){
				ServerAccess.activityName = ""; 
			}
			else{
				musicPlayer.startPlay();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	private View.OnClickListener v2OnClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			if(v.getId() == R.id.collect_btn) {
				if(isOnline && ServerAccess.uid > 0){
					HashMap<String, Object> map = mOlineMusicList.get(MusicPlayer.position);
					
					DatabaseUtil db = new DatabaseUtil(MusicPlayerActivity.this);
					music_uid = Integer.parseInt(map.get("index").toString());
					
					if(!db.haveConllect(music_uid)) {
						//写入本地
						db.insertConllect(music_uid, ServerAccess.uid);
						
						//写入网络
						Thread thread = new Thread(delRunnable);
						thread.start();
						
						//收藏成功
						Toast.makeText(MusicPlayerActivity.this, "收藏成功!", Toast.LENGTH_LONG).show();
					}
				}
			}
			else if(v.getId() == R.id.download_btn) {
				if(isOnline){
					HashMap<String, Object> map = mOlineMusicList.get(MusicPlayer.position);
				
					DatabaseUtil db = new DatabaseUtil(MusicPlayerActivity.this);
					int uid = Integer.parseInt(map.get("index").toString());
					if(!db.haveDownload(uid))
					{
						GlobalValue.g_DownloadManager.addDownload(map);
						Toast.makeText(MusicPlayerActivity.this, "已加入下载!", Toast.LENGTH_LONG).show();
					}
				}
			}
		}
	};
	
	//删除收藏
		//BY Kress
		protected Runnable delRunnable = new Runnable() {
			
			@Override
			public void run() {
				try {
					serverAccess.addToConllect(music_uid, ServerAccess.uid, new String[]{});

				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		};

	private void setListView() {
		musiclist = new ArrayList<HashMap<String, String>>();
		if (isOnline) {
			for (int i = 0; i < mOlineMusicList.size(); i++) {
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("playerName",
						mOlineMusicList.get(i).get(ServerAccess.SINGER)
								.toString());
				map.put("musicName",
						mOlineMusicList.get(i).get(ServerAccess.MUSIC_NAME)
								.toString());
				map.put("index",
						mOlineMusicList.get(i).get(ServerAccess.INDEX)
								.toString());
				map.put("icon_url", mOlineMusicList.get(i).get(ServerAccess.ICON_URL)
						.toString());
				musiclist.add(map);
			}
			String keys[] = new String[] { "musicName","playerName"};
			mAdapter = new MusicPlayMusicAdapter(this, musiclist, new int[] {
					R.id.musicName, R.id.playerName}, keys,
					new String[] { ServerAccess.ICON_URL },
					new int[] { R.id.face }, R.drawable.bg_play_scro,
					R.layout.music_play_list);
			mAdapter.addInterfaceOnMore(mMoreInterface);
			musicListView.setAdapter(mAdapter);
		} else {
			if (MusicPlayer.musicInfos != null) {
				for (int i = 0; i < MusicPlayer.musicInfos.size(); i++) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("playerName", MusicPlayer.musicInfos.get(i)
							.getArtist());
					map.put("musicName", MusicPlayer.musicInfos.get(i)
							.getTitle());
					musiclist.add(map);
				}
			}
			String keys[] = new String[] { "musicName","playerName"};
			mAdapter = new MusicPlayMusicAdapter(this, musiclist, new int[] {
					R.id.musicName, R.id.playerName}, keys,
					new String[] { ServerAccess.ICON_URL },
					new int[] { R.id.face }, R.drawable.icon_music_default,
					R.layout.music_play_list);
			mAdapter.addInterfaceOnMore(mMoreInterface);
			musicListView.setAdapter(mAdapter);
		}

	}
	//添加List回调事件
		private MusicPlayMoreInterface mMoreInterface = new MusicPlayMoreInterface() {
			@Override
			public void OnClickDownload(final int position) {
				
				if(isOnline){
					HashMap<String, Object> map = mOlineMusicList.get(position);
				
					GlobalValue.g_DownloadManager.addDownload(map);
				
					Toast.makeText(MusicPlayerActivity.this, "已加入下载!", Toast.LENGTH_LONG).show();
				}
			}

			@Override
			public void OnClickConllect(int position) {
				if(position==MusicPlayer.position){
					if(isOnline){
						
						MusicPlayer.position = MusicPlayer.position-1;
						musiclist.remove(position);
						musicPlayer.next_music();
						mOlineMusicList.remove(position);
						mAdapter.notifyDataSetChanged();
						setTextView();
						Toast.makeText(MusicPlayerActivity.this, "已移除歌曲",
								Toast.LENGTH_SHORT).show();
					}
					else{
						MusicPlayer.position = MusicPlayer.position-1;
						musicPlayer.next_music();
						setTextView();
						PlayService.mp3Infos.remove(position);
						musiclist.remove(position);
						mAdapter.notifyDataSetChanged();
						Toast.makeText(MusicPlayerActivity.this, "已移除歌曲",
								Toast.LENGTH_SHORT).show();
					}
				}
				else if(position<MusicPlayer.position){
					if(isOnline){
						
						musiclist.remove(position);
						mOlineMusicList.remove(position);
						MusicPlayer.position --;
						mAdapter.notifyDataSetChanged();
						Toast.makeText(MusicPlayerActivity.this, "已移除歌曲",
								Toast.LENGTH_SHORT).show();
					}
					else{
						if(PlayService.mp3Infos != null)
						PlayService.mp3Infos.remove(position);
						musiclist.remove(position);
						MusicPlayer.position --;
						mAdapter.notifyDataSetChanged();
						Toast.makeText(MusicPlayerActivity.this, "已移除歌曲",
								Toast.LENGTH_SHORT).show();
					}
				}
				else{
					if(isOnline){
						
						musiclist.remove(position);
						mOlineMusicList.remove(position);
						mAdapter.notifyDataSetChanged();
						Toast.makeText(MusicPlayerActivity.this, "已移除歌曲",
								Toast.LENGTH_SHORT).show();
					}
					else{
						if(PlayService.mp3Infos != null)
						PlayService.mp3Infos.remove(position);
						musiclist.remove(position);
						mAdapter.notifyDataSetChanged();
						Toast.makeText(MusicPlayerActivity.this, "已移除歌曲",
								Toast.LENGTH_SHORT).show();
					}
				}
			}
		};

	private View.OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			// 播放或者暂停
			case R.id.playBtn: {
				if(mAdapter.getCount() <= 0)
					return;
				
				if (MusicPlayer.isPlaying) {
					playBtn.setBackgroundResource(R.drawable.btn_playing_normal);
				}
				else {
					playBtn.setBackgroundResource(R.drawable.btn_play_stop_normal);
				}
				musicPlayer.play();
			}
				break;
			// 上一首
			case R.id.last_music: {
				if(mAdapter.getCount() <= 0)
					return;
				if (MusicPlayer.position == 0) {
					Toast.makeText(MusicPlayerActivity.this, "没有上一首了哦",
							Toast.LENGTH_SHORT).show();
					break;
				} 
				else
				if(MusicPlayer.isPlaying==false){
					MusicPlayer.isPlaying =  true;
					playBtn.setBackgroundResource(R.drawable.btn_play_stop_normal);
				}
				
					musicPlayer.previous_music();
					setTextView();
				
				mAdapter.notifyDataSetChanged();
			}
				break;
			// 下一首
			case R.id.next_music: {
				if (MusicPlayer.position ==mAdapter.getCount()) {
					Toast.makeText(MusicPlayerActivity.this, "没有下一首了哦",
							Toast.LENGTH_SHORT).show();
					break;
				} 
				else
				if(MusicPlayer.isPlaying==false){
					MusicPlayer.isPlaying =  true;
					playBtn.setBackgroundResource(R.drawable.btn_play_stop_normal);
					
				}
				musicPlayer.next_music();
				setTextView();
				mAdapter.notifyDataSetChanged();
			}
				break;
			// 播放模式
			case R.id.shuffle_music: {
				musicPlayer.shuffle_music();
				if (MusicPlayer.PLAY_ORDER == 1) {
					shuffleMusicBtn
							.setBackgroundResource(R.drawable.shuffle_music1);
					Toast.makeText(MusicPlayerActivity.this, "随机模式",
							Toast.LENGTH_SHORT).show();
				}
				else if (MusicPlayer.PLAY_ORDER == 3) {
					shuffleMusicBtn.setBackgroundResource(R.drawable.one_play);
					Toast.makeText(MusicPlayerActivity.this, "单曲模式",
							Toast.LENGTH_SHORT).show();
				}
				else if (MusicPlayer.PLAY_ORDER == 0) {
					shuffleMusicBtn
							.setBackgroundResource(R.drawable.repeat_play);
					Toast.makeText(MusicPlayerActivity.this, "顺序模式",
							Toast.LENGTH_SHORT).show();
				}
			}
				break;
			case R.id.downImgBtn: {
				finish();
				overridePendingTransition(android.R.anim.fade_in,
						R.anim.overview_close);
			}
				break;

			case R.id.smaller_menus: {
				
				if(mAdapter.getCount() <= 0)
					return;
				
				if (moreLay.getVisibility() == View.VISIBLE) {
					moreLay.setVisibility(View.GONE);
				} else {
					moreLay.setVisibility(View.VISIBLE);
				}
			}
			break;
			case R.id.music_play_share_btn:{
				 
				if(mAdapter.getCount() <= 0)
					return;
				
				OnekeyShare oks = new OnekeyShare();
				
				if(MusicPlayerActivity.isOnline) {
					HashMap<String, Object> map = mOlineMusicList.get(MusicPlayer.position);
					oks.setText("我在雪域音乐App上发现一首很好听的歌<" + map.get(ServerAccess.MUSIC_NAME).toString() 
							+ "> 分享给大家听听。");
				}else {
					HashMap<String, String> map = musiclist.get(MusicPlayer.position);
					oks.setText("我在雪域音乐App上发现一首很好听的歌<" + map.get("musicName").toString() 
							+ "> 分享给大家听听。");
				}
				
				// 分享时Notification的图标和文字
				oks.setNotification(R.drawable.ic_launcher, 
				"分享");
				// text是分享文本，所有平台都需要这个字段
				

				// 是否直接分享（true则直接分享）
				oks.setSilent(false);

				// 去除注释可通过OneKeyShareCallback来捕获快捷分享的处理结果
				// oks.setCallback(new OneKeyShareCallback());
				//通过OneKeyShareCallback来修改不同平台分享的内容
				oks.setShareContentCustomizeCallback(
				new ShareContentCustomizeCallback() {
					
					@Override
					public void onShare(Platform platform, ShareParams paramsToShare) {
						// TODO Auto-generated method stub
						
					}
				});

				oks.show(MusicPlayerActivity.this);
			}
			break;
			case R.id.music_play_album_btn:{
				
				getSingerOrAblum = ServerAccess.ALBUM;
				
				try {
					if(MusicPlayerActivity.isOnline){
						
						//
						HashMap<String, Object> map = MusicPlayerActivity.mOlineMusicList.get(MusicPlayer.position);
						album = map.get(ServerAccess.ALBUM).toString();
					}
					else{
						HashMap<String, String> map = musiclist
								.get(MusicPlayer.position);
						album = map.get(ServerAccess.ALBUM);
					}
					
					if(album == null || album.equals("")){
						Toast.makeText(MusicPlayerActivity.this, "没有相应的专辑信息",
								Toast.LENGTH_SHORT).show();
						
						return;
					}

					mLoadMask.startLoad();
					accThread = new Thread(runnable);
					accThread.start();
				} catch (Exception e) {
					// TODO: handle exception
				}
				
			
			}
			break;
			case R.id.music_play_add_btn:{
				if(isOnline==true){
					Toast.makeText(MusicPlayerActivity.this, "在线音乐暂不支持添加到列表",
							Toast.LENGTH_SHORT).show();
					
				}
				else{
					ServerAccess.activityName = "MusicPlayerActivity";
					 String  musicName = MusicPlayer.musicInfos.get(
								MusicPlayer.position).getTitle().toString();
					 String  playerName =MusicPlayer.musicInfos.get(
								MusicPlayer.position).getArtist();
					 String  duration = MusicPlayer.musicInfos.get(MusicPlayer.position).getDuration()+"";
					 String  size = MusicPlayer.musicInfos.get(MusicPlayer.position).getSize()+"";
					 String  url = MusicPlayer.musicInfos.get(
								MusicPlayer.position).getUrl();
					 ServerAccess.AddOneMusicToMenu = true;
					 HashMap<String, Object>  musicMap= new HashMap<String, Object>();
					 musicMap.put("title",musicName);
					 musicMap.put("Artist",playerName);
					 musicMap.put("duration",duration);
					 musicMap.put("size",size);
					 musicMap.put("url",url);
					 ServerAccess.musicMap = musicMap;
					 Intent intent = new Intent(MusicPlayerActivity.this,EditAddTo.class);
					 startActivity(intent);
				}
			}
			break;
			case R.id.music_play_singer_btn: {
				
				try {
					getSingerOrAblum = ServerAccess.SINGER;
					if (isOnline == false) {

						HashMap<String, String> map = musiclist
								.get(MusicPlayer.position);
						singer = map.get("playerName");

					} else {
						singer = MusicPlayerActivity.mOlineMusicList
								.get(MusicPlayer.position).get(ServerAccess.SINGER)
								.toString();
					}
					
					if (singer == null || singer.equals("")) {
						Toast.makeText(MusicPlayerActivity.this, "没有相应的歌手歌曲",
								Toast.LENGTH_SHORT).show();

						return;
					}
					
					mLoadMask.startLoad();
					accThread = new Thread(runnable);
					accThread.start();
				}catch (Exception e) {
					// TODO: handle exception
				}
			}
				break;
			default:
				break;
			}
		}
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
		{
			finish();
			
			overridePendingTransition(android.R.anim.fade_in,
					R.anim.overview_close);
		}
			break;

		default:
			break;
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	private void initGlobalValue() {
		GlobalValue.initSDAddr();

		GlobalValue.addUrl(ServerAccess.GETALBUMID,
				"http://www.snowmusic.com.cn/mobile_api/getAlbumId.php");
		GlobalValue.addUrl(ServerAccess.GETSINGERID,
				"http://www.snowmusic.com.cn/mobile_api/getSingerId.php");
	}

	public class MyOnPageChangeListener implements OnPageChangeListener {

		public void onPageSelected(int page) {
			// 翻页时当前page,改变当前状态园点图片
			switch (page) {
			case 0:
				mPage0.setImageDrawable(getResources().getDrawable(
						R.drawable.viewpage_on));
				mPage1.setImageDrawable(getResources().getDrawable(
						R.drawable.viewpage_out));
				mPage2.setImageDrawable(getResources().getDrawable(
						R.drawable.viewpage_out));
				break;
			case 1:
				mPage0.setImageDrawable(getResources().getDrawable(
						R.drawable.viewpage_out));
				mPage1.setImageDrawable(getResources().getDrawable(
						R.drawable.viewpage_on));
				mPage2.setImageDrawable(getResources().getDrawable(
						R.drawable.viewpage_out));
				break;
			case 2:
				mPage2.setImageDrawable(getResources().getDrawable(
						R.drawable.viewpage_on));
				mPage1.setImageDrawable(getResources().getDrawable(
						R.drawable.viewpage_out));
				mPage0.setImageDrawable(getResources().getDrawable(
						R.drawable.viewpage_out));
				break;

			}
		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		public void onPageScrollStateChanged(int arg0) {

		}
	}



	@Override
	protected void onStop() {
		// 取消注册
		sensorManager.unregisterListener(this);
		super.onStop();
	}

	/**
	 * 覆写SensorListener的方法，传感器值变化时调用
	 * 
	 */
	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		// 获取当前震动位置
		// TODO Auto-generated method stub
		// 现在检测时间
		long currentUpdateTime = System.currentTimeMillis();
		// 两次检测的时间间隔
		long timeInterval = currentUpdateTime - lastUpdateTime;
		// 判断是否达到了检测时间间隔
		if (timeInterval < UPTATE_INTERVAL_TIME)
			return;
		// 现在的时间变成last时间
		lastUpdateTime = currentUpdateTime;

		// 获得x,y,z坐标
		float x = event.values[0];
		float y = event.values[1];
		float z = event.values[2];

		// 获得x,y,z的变化值
		float deltaX = x - lastX;
		float deltaY = y - lastY;
		float deltaZ = z - lastZ;

		// 将现在的坐标变成last坐标
		lastX = x;
		lastY = y;
		lastZ = z;

		double speed = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ
				* deltaZ)
				/ timeInterval * 10000;
		// 达到速度阀值，发出提示
		if (speed >= SPEED_SHRESHOLD) {
			System.out.println("下一首");
			musicPlayer.next_music();
			setTextView();
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	/**
	 * 设置textView中的值(歌名，歌手名)
	 */
	private void setTextView() {
		if (isOnline == true) {
			lay3_musicName.setText(mOlineMusicList.get(MusicPlayer.position)
					.get(ServerAccess.MUSIC_NAME).toString());
			lay3_playerName.setText(mOlineMusicList.get(MusicPlayer.position)
					.get(ServerAccess.SINGER).toString());

		} else {
			if (MusicPlayer.musicInfos != null) {
				lay3_musicName.setText(MusicPlayer.musicInfos.get(
						MusicPlayer.position).getTitle());
				lay3_playerName.setText(MusicPlayer.musicInfos.get(
						MusicPlayer.position).getArtist());
			}
		}

	}
	
	public static  void setMusicImg(){
		if(isOnline == true){
			mImageLoader.DisplayImage(mOlineMusicList.get(MusicPlayer.position)
					.get(ServerAccess.ICON_URL).toString(),image1, false,R.drawable.trans);
			mImageLoader.DisplayImage(mOlineMusicList.get(MusicPlayer.position)
					.get(ServerAccess.ICON_URL).toString(),image2, false,R.drawable.trans);
			mImageLoader.DisplayImage(mOlineMusicList.get(MusicPlayer.position)
					.get(ServerAccess.ICON_URL).toString(),image3, false,R.drawable.trans);		
		}
	}

	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

	}
	
	//TODO: inteface
	private PlayerInterface playerInterface = new PlayerInterface() {

		@Override
		public void playNext(int position) {
			mPosition = position;
			MusicPlayer.position = position;
			mAdapter.notifyDataSetChanged();
			
			musicListView.setSelection(MusicPlayer.position);
		}
		 
	};

	protected Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				if(getSingerOrAblum.equals(ServerAccess.ALBUM)){
					netDate = serverAccess.GetAblumAtmusicPlay(MusicPlayerActivity.mOlineMusicList.get(MusicPlayer.position).get(ServerAccess.ALBUM).toString());
					sendMessage(2);
				}
				else{
					netDate = serverAccess.GetPlayerAtmusicPlay(singer);
					sendMessage(UPDATE_DATA);
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	};
	// 发送消息到Handler
		private void sendMessage(int what) {
			Message msg = new Message();
			msg.what = what;
			handler.sendMessage(msg);
		}
		protected Handler handler = new Handler() {
			@SuppressWarnings("unchecked")
			@Override
			public void handleMessage(Message msg) {

				try {
					switch (msg.what) {
					case UPDATE_DATA: {
						String index = netDate;
						mLoadMask.stopLoad();
						
						System.out.println("----------------" + index);
						if (!index.equals("") && !index.equals("no")) {
							Intent intent = new Intent(MusicPlayerActivity.this,
									OnlinePlayerContentListActivity.class);

							intent.putExtra(ServerAccess.INDEX, index);
							intent.putExtra(ServerAccess.SINGER, singer);
							startActivity(intent);
						} else {
							Toast.makeText(MusicPlayerActivity.this, "没有相应的歌手歌曲",
									Toast.LENGTH_SHORT).show();
						}
					}
						break;
					case 2:
					{
						String index = netDate;
						mLoadMask.stopLoad();
						
						if(!index.equals("")&&!index.equals("no")){
							Intent intent = new Intent(MusicPlayerActivity.this,OnlineSpecialContentActivity.class);
							intent.putExtra(ServerAccess.INDEX, index);
							intent.putExtra(ServerAccess.SINGER, singer);
							intent.putExtra(ServerAccess.ALBUM, album);
							startActivity(intent);
						}
						else{
							Toast.makeText(MusicPlayerActivity.this, "没有相应的专辑信息",
									Toast.LENGTH_SHORT).show();
						}
					}
						break;
					default:
						break;
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				
				super.handleMessage(msg);
			}
		};

}
